package com.ml.tools;

import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore.Images.ImageColumns;
import android.text.Html;
import android.text.Spanned;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.ml.app.MyApplication;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@SuppressLint("SimpleDateFormat")
public class Utils {
    /**
     *
     */
    public static final String ACTION_MEDIA_SCANNER_SCAN_DIR = "android.intent.action.MEDIA_SCANNER_SCAN_DIR";
    @SuppressWarnings("unused")
    private static final double PI = 3.14159265;
    private static final double RAD = Math.PI / 180.0;
    private static final double EARTH_RADIUS = 6378137.0;
    public static SimpleDateFormat DB_TIMESTAMP_Format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    public static SimpleDateFormat LOCATION_Format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public static double getDistance(double longitude1, double latitude1, double longitude2, double latitude2) {
        double Lat1 = rad(latitude1);
        double Lat2 = rad(latitude2);
        double a = Lat1 - Lat2;
        double b = rad(longitude1) - rad(longitude2);
        double s = 2 * Math.asin(Math
                .sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(Lat1) * Math.cos(Lat2) * Math.pow(Math.sin(b / 2), 2)));
        s = s * EARTH_RADIUS;
        s = Math.round(s * 10000) / 10000;
        return s;
    }

    public static long transDateStringToLong6(String time) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            return sdf.parse(time).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0;
    }

    public static String transLongToDateString(long time) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date date = new Date(time);
        return sdf.format(date);
    }

    public static String transLongToDateString5(long time) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date(time);
        return sdf.format(date);
    }

    public static String transLongToDateString3(long time) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date(time);
        return sdf.format(date);
    }

    public static void makeRootDirectory(String filePath) {
        File file = null;
        String newPath = null;
        String[] path = filePath.split("/");
        for (int i = 0; i < path.length; i++) {
            if (newPath == null) {
                newPath = path[i];
            } else {
                newPath = newPath + "/" + path[i];
            }
            file = new File(newPath);
            if (!file.exists()) {
                file.mkdir();
            }
        }
    }

    public static String transLongToDateString2(long time) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
        Date date = new Date(time);
        return sdf.format(date);
    }

    public static long transDateStringToLong(String time) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        try {
            return sdf.parse(time).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0;
    }

    public static long transDateStringToLong5(String time) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            return sdf.parse(time).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0;
    }

    public static long transDateStringToLong2(String time) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        try {
            return sdf.parse(time).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * @param lng1
     * @param lat1
     * @param lng2
     * @param lat2
     * @return
     */
    public static double getBaiduDistance(double lng1, double lat1, double lng2, double lat2) {
        double radLat1 = lat1 * RAD;
        double radLat2 = lat2 * RAD;
        double a = radLat1 - radLat2;
        double b = (lng1 - lng2) * RAD;
        double s = 2 * Math.asin(Math.sqrt(
                Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
        s = s * EARTH_RADIUS;
        s = Math.round(s * 10000) / 10000;
        System.out.println(s);
        return s;
    }

    // public static String getVersion() {
    // String version = "";
    // try {
    // PackageManager manager = KindergartenApplication.getInstance()
    // .getApplicationContext().getPackageManager();
    // PackageInfo info = manager.getPackageInfo(KindergartenApplication
    // .getInstance().getApplicationContext().getPackageName(), 0);
    // version = info.versionName;
    // } catch (Exception e) {
    // e.printStackTrace();
    // }
    // return version;
    // }

    private static double rad(double d) {
        return d * Math.PI / 180.0;
    }

    public static int getUid(Context context) {
        try {
            PackageManager pm = context.getPackageManager();
            @SuppressLint("WrongConstant") android.content.pm.ApplicationInfo ai = pm.getApplicationInfo("com.ugoodtech.android.kindergarten",
                    PackageManager.GET_ACTIVITIES);
            Log.d("!!", "!!" + ai.uid);
            return ai.uid;
        } catch (android.content.pm.PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return -1;
        }
    }

    public static void scanDirAsync(Context ctx, String dir) {
        Intent scanIntent = new Intent(ACTION_MEDIA_SCANNER_SCAN_DIR);
        scanIntent.setData(Uri.fromFile(new File(dir)));
        ctx.sendBroadcast(scanIntent);
    }

    /**
     * @param ctx
     * @param filePath
     */

    public static void scanFileAsync(Context ctx, String filePath) {
        Intent scanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        scanIntent.setData(Uri.fromFile(new File(filePath)));
        ctx.sendBroadcast(scanIntent);
    }

    /**
     *
     */
    public static String getAppVersionName(Context context) {
        String versionName = "";
        try {
            // ---get the package info---
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
            versionName = pi.versionName;
            // versioncode = pi.versionCode;
            if (versionName == null || versionName.length() <= 0) {
                return "";
            }
        } catch (Exception e) {
            Log.e("VersionInfo", "Exception", e);
        }
        return versionName;
    }

    public static int compare(String v1, String v2) {
        String s1 = normalisedVersion(v1);
        String s2 = normalisedVersion(v2);
        return s1.compareTo(s2);
    }

    public static String normalisedVersion(String version) {
        return normalisedVersion(version, ".", 4);
    }

    public static String normalisedVersion(String version, String sep, int maxWidth) {
        String[] split = Pattern.compile(sep, Pattern.LITERAL).split(version);
        StringBuilder sb = new StringBuilder();
        for (String s : split) {
            sb.append(String.format("%" + maxWidth + 's', s));
        }
        return sb.toString();
    }

    public static boolean checkpwd(String pwd) {

        Pattern p = Pattern.compile("[0-9A-Za-z]*");

        Matcher m = p.matcher(pwd);

        System.out.println(m.matches() + "---");

        return m.matches();

    }

    public static boolean isSDCardExist() {
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    }

    public static File getWorkDir() {
        File dir = null;
        try {
            String destDir = Environment.getExternalStorageDirectory().getPath() + File.separator + "FmsAndroid";
            dir = new File(destDir);
        } catch (Exception x) {
            dir = Environment.getDownloadCacheDirectory();
        }
        if (!dir.exists())
            dir.mkdirs();
        return dir;
    }

    public static void showToast(Context context, String text) {
        Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
    }

    public static void showToast(Context context, int resId) {
        Toast.makeText(context, context.getResources().getString(resId), Toast.LENGTH_SHORT).show();
    }

    public static String getRefreshTime() {
        return DB_TIMESTAMP_Format.format(new Date());
    }

    public static String getStandardTime() {
        return LOCATION_Format.format(new Date());
    }

    public static boolean isMobileNO(String mobiles) {
        Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0-9]))\\d{8}$");
        Matcher m = p.matcher(mobiles);
        return m.matches();
    }

    public static void hideSystemKeyBoard(Context context, View view) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

    public static void showSystemKeyBoard(Context context, View view) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(view, 0);
    }

    public static boolean isNetworkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable();
            }
        }
        return false;
    }

    public static boolean toastIsNetworkConnected(Context context) {
        boolean l = isNetworkConnected(context);
        return l;
    }

    public static void focusOnError(Context context, TextView field, int resourceId) {
        field.requestFocus();
        hideSystemKeyBoard(context, field);
        field.setError("<font color=#333333>" + context.getString(resourceId) + "</font>");
    }

    public static void focusOnError(Context context, EditText field, String message) {
        field.requestFocus();
        hideSystemKeyBoard(context, field);
        Spanned fromHtml = Html.fromHtml("<font color=#333333>" + message + "</font>");
        field.setError(fromHtml);
        // field.clearFocus();
    }

    /**
     * Create a file Uri for saving an image or video
     */
    public static Uri getOutputMediaFileUri() {
        File mediaFile = getOutputMediaFile();
        if (mediaFile == null) {
            return null;
        } else {
            return Uri.fromFile(mediaFile);
        }
    }

    public static File getOutputMediaStorageDir() {
        // To be safe, you should check that the SDCard is mounted
        // using Environment.getExternalStorageState() before doing this.
        File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                "p009");

        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                return null;
            }
        }
        return mediaStorageDir;
    }

    /**
     * Create a File for saving an image or video
     */
    public static File getOutputMediaFile() {
        File mediaStorageDir = getOutputMediaStorageDir();
        // Create a media file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        File mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");
        Log.d("kindergarten", "temp path:" + mediaFile.getPath());
        return mediaFile;
    }

    public static String getSDPath() {
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED); //
        if (sdCardExist) {
            sdDir = Environment.getExternalStorageDirectory();//
        } else {
            sdDir = Environment.getRootDirectory();
        }
        return sdDir.toString();

    }

    public static boolean createDir(String destDirName) {
        File dir = new File(destDirName);
        if (dir.exists()) {
            return false;
        }
        if (!destDirName.endsWith(File.separator)) {
            destDirName = destDirName + File.separator;
        }
        return dir.mkdirs();
    }

    public static String getVersion() {
        String version = "";
        try {
            PackageManager manager = MyApplication.getInstance().getApplicationContext().getPackageManager();
            PackageInfo info = manager
                    .getPackageInfo(MyApplication.getInstance().getApplicationContext().getPackageName(), 0);
            version = info.versionName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return version;
    }

    public static int getVersionCode() {
        int version = 0;
        try {
            PackageManager manager = MyApplication.getInstance().getApplicationContext().getPackageManager();
            PackageInfo info = manager
                    .getPackageInfo(MyApplication.getInstance().getApplicationContext().getPackageName(), 0);
            version = info.versionCode;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return version;
    }

    public static boolean deleteDirectory(String sPath) {
        if (!sPath.endsWith(File.separator)) {
            sPath = sPath + File.separator;
        }
        File dirFile = new File(sPath);
        if (!dirFile.exists() || !dirFile.isDirectory()) {
            return false;
        }
        boolean flag = true;
        File[] files = dirFile.listFiles();
        for (int i = 0; i < files.length; i++) {
            if (files[i].isFile()) {
                flag = deleteFile(files[i].getAbsolutePath());
                if (!flag)
                    break;
            } else {
                flag = deleteDirectory(files[i].getAbsolutePath());
                if (!flag)
                    break;
            }
        }
        if (!flag)
            return false;
        return dirFile.delete();
    }

    public static boolean deleteDirectorySon(String sPath) {

        if (!sPath.endsWith(File.separator)) {
            sPath = sPath + File.separator;
        }
        File dirFile = new File(sPath);

        if (!dirFile.exists() || !dirFile.isDirectory()) {
            return false;
        }
        boolean flag = true;

        File[] files = dirFile.listFiles();
        for (int i = 0; i < files.length; i++) {
            if (files[i].isFile()) {
                flag = deleteFile(files[i].getAbsolutePath());
                if (!flag)
                    break;
            } else {
                flag = deleteDirectory(files[i].getAbsolutePath());
                if (!flag)
                    break;
            }
        }
        return flag;
    }

    public static boolean deleteFile(String sPath) {
        boolean flag = false;
        File file = new File(sPath);
        if (file.isFile() && file.exists()) {
            file.delete();
            flag = true;
        }
        return flag;
    }

    public static String getRealFilePath(final Uri uri, final Context ctx) {
        if (null == uri)
            return null;
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null)
            data = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = ctx.getContentResolver().query(uri, new String[]{ImageColumns.DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }

    public static boolean isOpenGps(Context context) {
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    }

    public static boolean retrieveApkFromAssets(Context context, String fileName, String path) {
        boolean bRet = false;

        try {
            File file = new File(path);
            if (file.exists()) {
                return true;
            } else {
                file.createNewFile();
                InputStream is = context.getAssets().open(fileName);
                FileOutputStream fos = new FileOutputStream(file);

                byte[] temp = new byte[1024];
                int i = 0;
                while ((i = is.read(temp)) != -1) {
                    fos.write(temp, 0, i);
                }
                fos.flush();
                fos.close();
                is.close();

                bRet = true;
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return bRet;
    }

    public static boolean isAppInstalled(Context context, String packagename) {
        PackageInfo packageInfo;
        try {
            packageInfo = context.getPackageManager().getPackageInfo(packagename, 0);
        } catch (NameNotFoundException e) {
            packageInfo = null;
            e.printStackTrace();
        }
        return packageInfo != null;
    }

    public static HashMap<String, String> setString() {
        HashMap<String, String> map = new HashMap<String, String>();
        if (MyApplication.yy.equals("vi")) {
            map.put("login", "Đăng nhập");
            map.put("networksetting", "Cài đặt mạng");
            map.put("input_username", "Xin vui lòng nhập tên người dùng");
            map.put("input_password", "Xin vui lòng nhập mật khẩu");
            map.put("input_ipport", "Xin vui lòng cài đặt mạng");
            map.put("network_error_try_again", "Không tìm thấy đường dây mạng có thể sử dụng xin hãy kiểm tra đường dây mạng kết nối của bạn");
            map.put("Easement", "Easement");

            map.put("save", "Lưu lại");
            map.put("success", "Thành công");
            map.put("fail", "Thất bại");
            map.put("input_ip", "Xin vui lòng nhập IP");
            map.put("port", "Cổng port");
            map.put("status", "Tình trạng");
            map.put("refresh", "Làm mới");
            map.put("inputport", "Xin vui lòng nhập cổng port");

            map.put("productlinename", "Sản xuất tên");
            map.put("people_num", "Số người lao động");
            map.put("todaytag", "Ngày nay mục tiêu");
            map.put("po", "Mệnh lệnh");
            map.put("tagpph", "Mục tiêu PPH");
            map.put("todaytag1", "Mục tiêu hiện tại");
            map.put("FTT", "FTT");
            map.put("shichang", "Thời");
            map.put("dqcl", "Sản lượng hiện tại");
            map.put("dcl", "Tỷ lệ thỏa");
            map.put("yichang", "Bất thường mạng");
            map.put("npph", "PPH");

            map.put("左鞋头", "Mũi giày trái");
            map.put("左前掌外腰", "Eo ngoài trước bên trái");
            map.put("左前掌内腰", "Eo trong trước bên trái");
            map.put("右前掌外腰", "Eo ngoài trước bên phải");
            map.put("右前掌内腰", "Eo trong trước bên phải");
            map.put("右鞋头", "Mũi giày phải");
            map.put("左鞋身内腰", "Eo trong thân giày trái");
            map.put("右鞋身内腰", "Eo trong thân giày phải");
            map.put("左鞋身外腰", "Eo ngoài thân giày trái");
            map.put("右鞋身外腰", "Eo ngoài thân giày phải");
            map.put("右鞋跟", "Gót chân phải");
            map.put("左鞋跟", "Gót chân trái");
            map.put("未知", "Chưa");
        } else if (MyApplication.yy.equals("en")) {
            map.put("login", "Log in");
            map.put("networksetting", "Network settings");
            map.put("input_username", "Please enter user name");
            map.put("input_password", "Please enter password");
            map.put("input_ipport", "Please set up the network first");
            map.put("network_error_try_again", "The server’s request failed or the network generated an exception");
            map.put("Easement", "Easement");
            map.put("save", "Save");
            map.put("success", "Success");
            map.put("fail", "Failed");
            map.put("input_ip", "Please enter IP");
            map.put("port", "Port");
            map.put("status", "status");
            map.put("refresh", "Refresh");
            map.put("inputport", "Please enter port");

            map.put("productlinename", "Prod.line");
            map.put("people_num", "Workers Number");
            map.put("todaytag", "Today goal");
            map.put("po", "Po");
            map.put("tagpph", "Target PPH");
            map.put("todaytag1", "Current Goal");
            map.put("FTT", "FTT");
            map.put("shichang", "Working hours");
            map.put("dqcl", "Current Yield");
            map.put("dcl", "Yield Rate");
            map.put("yichang", "Network Anomaly");
            map.put("npph", "PPH");

            map.put("左鞋头", "Left toe");
            map.put("左前掌外腰", "Left forefoot outer waist");
            map.put("左前掌内腰", "Left forepaw medial lumbar");
            map.put("右前掌外腰", "Right forefoot outer waist");
            map.put("右前掌内腰", "Right forepaw medial lumbar");
            map.put("右鞋头", "Right toe");
            map.put("左鞋身内腰", "Left body inside waist");
            map.put("右鞋身内腰", "Right body inside waist");
            map.put("左鞋身外腰", "Left body outer waist");
            map.put("右鞋身外腰", "Right body outer waist");
            map.put("右鞋跟", "Right heel");
            map.put("左鞋跟", "Left heel");
            map.put("未知", "Unknown");
        } else {
            map.put("login", "登录");
            map.put("networksetting", "网络设置");
            map.put("input_username", "请输入用户名");
            map.put("input_password", "请输入密码");
            map.put("input_ipport", "请先设置网络");
            map.put("network_error_try_again", "服务器请求失败或网络异常");
            map.put("Easement", "Easement");
            map.put("save", "保存");
            map.put("success", "成功");
            map.put("fail", "失败");
            map.put("input_ip", "请输入IP");
            map.put("port", "端口");
            map.put("status", "状态");
            map.put("refresh", "刷新");
            map.put("inputport", "请输入端口");

            map.put("productlinename", "产线名称");
            map.put("people_num", "工作人数");
            map.put("todaytag", "今日目标");
            map.put("po", "订单");
            map.put("tagpph", "目标PPH");
            map.put("todaytag1", "当前目标");
            map.put("FTT", "FTT");
            map.put("shichang", "时长");
            map.put("dqcl", "当前产量");
            map.put("dcl", "达成率");
            map.put("yichang", "网络异常");
            map.put("npph", "PPH");

            map.put("左鞋头", "左鞋头");
            map.put("左前掌外腰", "左前掌外腰");
            map.put("左前掌内腰", "左前掌内腰");
            map.put("右前掌外腰", "右前掌外腰");
            map.put("右前掌内腰", "右前掌内腰");
            map.put("右鞋头", "右鞋头");
            map.put("左鞋身内腰", "左鞋身内腰");
            map.put("右鞋身内腰", "右鞋身内腰");
            map.put("左鞋身外腰", "左鞋身外腰");
            map.put("右鞋身外腰", "右鞋身外腰");
            map.put("右鞋跟", "右鞋跟");
            map.put("左鞋跟", "左鞋跟");
            map.put("未知", "未知");
        }
        return map;
    }

}
